<template>
  <div class="container">
    <div>
      <div class="main_box_bottom" id="picDown">
        <div
          class="member_distribution"
          :style="{ width: '70%', height: '204px' }"
        >
          <div
            ref="member_distribution_pie"
            id="member_distribution_pie"
            class="chart_box"
          ></div>
        </div>
        <div class="legend" v-show="showLegend">
          <div class="legend_header">
            <label class="legend_header_label">
              <a-checkbox :checked="selectAll" @change="toggleAll('pie')">
                全选
              </a-checkbox>
            </label>
            <div class="pagination">
              <span class="pagination_text">{{
                `${displayedLegend}/${totalLegend}`
              }}</span>
            </div>
          </div>
          <div class="legend_column_content">
            <div class="legend_column">
              <div class="legend_body">
                <div
                  v-for="(item, index) in legendItem"
                  :key="item.name"
                  @click="toggleItem(item, index, 'pie')"
                  class="legend_item"
                >
                  <div
                    class="legend_item_circle"
                    :style="{
                      backgroundColor: item.check ? getColor(index) : '#CCCCCC',
                    }"
                  ></div>
                  <div
                    class="legend_item_label"
                    :style="{
                      color: item.check ? '#5c5c5c' : '#CCCCCC',
                    }"
                  >
                    <span class="legend_item_labe_text" :title="item.name">
                      {{ item.name }}</span
                    >
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { chart_data, PAR_COLOR } from "./constant.js";
import * as echarts from "echarts";

export default {
  name: "user_distribution",
  props: {
    byFields: Array,
  },
  data() {
    return {
      chart_data,
      echarts5: "",
      selectAll: true,
      legendData: {
        checkList: [], //图例列表
        selected: {}, //
        data: [],
      },
      baoCunPieData: null,
      baoCunBarLineData: null,
    };
  },
  computed: {
    // 展示的legend图例个数
    displayedLegend() {
      let num = 0;
      this.legendItem.forEach((item, index) => {
        if (item.check) {
          num++;
        }
      });
      return num;
    },
    // 总共的图例个数
    totalLegend() {
      return this.legendData.checkList.length;
    },
    legendItem() {
      return this.legendData.checkList;
    },
    // 数据是否为空
    showLegend() {
      if (this.chart_data.length == 0) return false;
      else return true;
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.echarts5 = echarts.init(this.$refs.member_distribution_pie, null, {
        renderer: "svg",
      });

      this.initEchartsData();
      this.chartResize();
    });
    window.addEventListener("resize", this.chartResize);
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.chartResize);
  },
  methods: {
    initClear() {
      this.echarts5 && this.echarts5.clear();
      this.selectAll = true;
      this.initEchartsData();
      this.$nextTick(() => {
        this.chartResize();
      });
    },
    // 初始化版本，系统，会员分布数据
    async initEchartsData() {
      this.getMemberDistributionPie(this.chart_data);
    },
    // 图表大小自适应
    chartResize() {
      this.echarts5.resize();
    },
    //获得饼图
    async getMemberDistributionPie(data) {
      let _c_1 = data;
      const pieChartData = [];
      let _legendData = {
        checkList: [],
        selected: {},
        data: [],
      };
      _c_1.forEach((obj) => {
        const _indicatorCal = obj.indicatorCal ? obj.indicatorCal : [];
        pieChartData.push({
          name: obj.byField,
          value: _indicatorCal,
          _indicatorCal: _indicatorCal,
          indictorName: obj.byField,
        });
        _legendData.data.push(obj.byField.toString());
        _legendData.selected[obj.byField.toString()] = true; //重要参数
        _legendData.checkList.push({
          name: obj.byField.toString(),
          check: true,
        });
      });
      this.legendData = _legendData;
      this.baoCunPieData = pieChartData;
      this.pieChartOption(this.legendData, pieChartData);
    },
    pieChartOption(legendData, pieChartData) {
      console.log("~ legendData", legendData);
      const emptyShow = pieChartData.every((item) => item._indicatorCal == 0);
      let option = {
        title: {
          show: pieChartData.length == 0 || emptyShow,
          textStyle: {
            color: "#ccc",
            fontSize: 18,
          },
          text: "数据为空",
          left: "center",
          top: "center",
        },
        tooltip: {
          trigger: "item",
          formatter: function (param) {
            return (
              param.data.indictorName +
              "<br>" +
              `<div style=\"display:inline-block;margin-bottom:2px;margin-right:4px;border-radius:3px;width:5px;height:5px;background-color:${param.color};\"></div>` +
              param.name +
              "   " +
              param.data._indicatorCal +
              "   " +
              +param.percent +
              "%" +
              "<br>"
            );
          },
          borderColor: "#EBEDEF",
          borderWidth: 1,
          borderRadius: 2,
          extraCssText: "box-shadow: 0 0 0px rgba(0, 0, 0, 0);",
          padding: [5, 18, 6, 9],
          textStyle: {
            color: "#676d74",
            fontSize: 12,
            lineHeight: 14,
            fontFamily: "ArialMT, ArialMT-Regular",
          },
          extraCssText:
            "border: 1px solid #ccc; background-color: rgba(255, 255, 255, 0.8);",
        },
        //饼图中各模块的颜色
        color: PAR_COLOR,
        // 饼图数据
        series: {
          type: "pie",
          center: ["33.4%", "50%"],
          minAngle: 4,
          top: 0,
          left: 0,
          bottom: 0,
          radius: [0, "95%"],
          data: pieChartData,
          // 设置showEmptyCircle为true，展示空心圆形
          showEmptyCircle: true,
          labelLine: {
            show: false,
          },
          label: {
            show: false,
          },
          emptyCircleStyle: {
            normal: {
              borderWidth: 2,
              borderColor: "#ccc",
            },
          },
        },
        legend: {
          show: false, //隐藏默认图例
          selected: legendData.selected,
          data: legendData.data,
          type: "scroll",
          orient: "vertical",
          right: 100,
          top: 0,
          width: 350,
          height: 170,
          icon: "circle",
          itemWidth: 8,
          itemGap: 12,
          itemHeight: 8,
          selectorPosition: "start",
          textStyle: {
            color: "rgba(92, 92, 92, 1)",
            fontWeight: "400",
            fontFamily: ["PingFang SC", "PingFang SC-Regular"],
            fontSize: 13,
            lineHeight: 18,
          },
          formatter(name) {
            // 超过指定字符省略显示
            return name.length > 10 ? `${name.substr(0, 10)}...` : name;
          },
        },
      };
      this.echarts5.setOption(option);
    },
    // 图例自定义点击事件
    toggleItem(item, index, type) {
      this.legendData.checkList[index].check =
        !this.legendData.checkList[index].check;
      this.legendData.selected[item.name] =
        !this.legendData.selected[item.name];
      this.selectAll = this.legendData.checkList.every((item) => item.check);
      this.reloadChart(type);
    },
    toggleAll(type) {
      this.selectAll = !this.selectAll;
      for (const key in this.legendData.selected) {
        // hasOwnProperty 方法来确保遍历的属性是 this.legendData.selected 自身的属性
        if (this.legendData.selected.hasOwnProperty(key)) {
          this.legendData.selected[key] = this.selectAll; // 将每一项设为this.selectAll的值
        }
      }
      this.legendData.checkList.forEach((item) => {
        item.check = this.selectAll;
      });
      this.reloadChart(type);
    },
    // 重新加载图表
    reloadChart(type) {
      if (type == "pie") {
        this.pieChartOption(this.legendData, this.baoCunPieData);
      }
    },
    getColor(index) {
      const color = PAR_COLOR;
      const colorIndex = index % color.length;
      return color[colorIndex];
    },
  },
};
</script>

<style lang="less" scoped>
.container {
  height: 204px;
  background: #ffffff;
  position: relative;
  border-radius: 8px;
  box-sizing: border-box;

  .main_box_bottom {
    box-sizing: border-box; 
    padding-top: 10px;
    .distribution_system,
    .member_distribution {
      width: 100%;
      min-height: 204px;
      background: #ffffff;

      .chart_box {
        width: 100%;
        height: 213px;
        padding: 17px 0 10px 0;
      }
    }

    .distribution_retained {
      margin-right: 16px;
      width: 50%;
      min-width: 553px;
      max-width: 830px;
      height: 251px;
    }

    .userusage_duration {
      width: 50%;
      min-width: 553px;
      max-width: 830px;
      height: 251px;
    }
  }

  .chart-container {
    display: flex;
    flex-direction: row;
    align-items: center;
  }

  .chart {
    width: 400px;
    height: 400px;
  }
  .legend {
    width: 30%;
    height: 204px;
    padding-left: 36px;
  }
  .legend_header {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-start;
    margin-bottom: 12px;
    font-size: 13px;
    color: #5c5c5c;
    /deep/ .legend_header_label {
      display: flex;
      .ant-checkbox-wrapper {
        height: 18px;

        color: #5c5c5c;
        .ant-checkbox {
          .ant-checkbox-inner {
            width: 12px;
            height: 12px;
            &::after {
              left: 1px;
            }
          }
        }
      }
    }
  }
  .legend_body {
    overflow-y: scroll;
    display: flex;
    flex-wrap: wrap;
    align-content: flex-start;
    width: 100%;
    height: 160px;
    .legend_item {
      width: 50%;
      height: 20px;
      display: flex;
      align-items: center;

      .legend_item_circle {
        width: 10px;
        height: 10px;
        margin-bottom: 2px;
        display: inline-block;
        border-radius: 50%;
        cursor: pointer;
      }
      .legend_item_label {
        flex: 1;
        min-width: 80px;
        height: 100%;
        margin: 0 6px;
        text-overflow: ellipsis;
        text-wrap: wrap;
        text-align: left;
        overflow: hidden;
        color: #5c5c5c;
        cursor: pointer;
        .legend_item_labe_text {
          text-wrap: nowrap;
          line-height: 20px;
          text-overflow: ellipsis;
          overflow: hidden;
        }
      }
      .pagination {
        .pagination_text {
          min-width: 17px;
          height: 14px;
          text-align: left;
          color: #8c8c8c;
          line-height: 14px;
          margin: 0 4px;
        }
      }
    }
  }
}
</style>
